package com.cyzy.controller;

import com.cyzy.dto.R;
import com.cyzy.service.ActivationCodeService;
import com.cyzy.service.LibraryService;
import com.cyzy.service.SubjectService;
import com.cyzy.vo.ExamLibraries;
import com.cyzy.vo.UserActivationCodes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/activationCode")
public class ActivationCodeController {

    @Autowired
    private ActivationCodeService activationCodeService;

    @Autowired
    private SubjectService subjectService;

    @Autowired
    private LibraryService libraryService;

    @PostMapping("/selectActivationCode")
    public R selectActivationCode(@RequestBody UserActivationCodes userActivationCodes){
        // 获取传入的 userId 和 activationCode
        long userId = userActivationCodes.getUserId();
        String activationCode = userActivationCodes.getActivationCode();

        // 查询激活码
        UserActivationCodes dbCode = activationCodeService
                .lambdaQuery()
                .eq(UserActivationCodes::getUserId, userId)
                .eq(UserActivationCodes::getActivationCode, activationCode)
                .one();

        // 如果激活码不存在
        if (dbCode == null) {
            return R.ok().code(500).message("无效的激活码");
        }

        // 如果激活码已经激活
        if (dbCode.getIsActivated() == 1) {
            return R.ok().code(500).message("该激活码已激活");
        }

        // 获取当前时间
        Timestamp currentTimestamp = Timestamp.valueOf(LocalDateTime.now());

        // 如果激活码过期
        if (dbCode.getValidUntil().before(currentTimestamp)) {
            return R.ok().code(500).message("无效的激活码");
        }

        // 如果激活码有效，且尚未激活
        dbCode.setIsActivated(1); // 设置为已激活
        dbCode.setValidFrom(currentTimestamp); // 设置 validFrom 为当前时间
        dbCode.setUpdatedAt(currentTimestamp);

        // 更新激活码状态
        boolean isUpdated = activationCodeService.updateById(dbCode);

        if (isUpdated) {
            return R.ok().code(200).message("激活码激活成功");
        } else {
            return R.ok().code(500).message("激活失败");
        }
    }

    @GetMapping("/getActivationCodeData")
    public R getActivationCodeData(@RequestParam("userId") long userId) {
        // 查询所有有效的激活码
        List<UserActivationCodes> activationCodes = activationCodeService
                .lambdaQuery()
                .eq(UserActivationCodes::getUserId, userId)
                .eq(UserActivationCodes::getIsActivated, 1)
                .eq(UserActivationCodes::getStatus, 1)
                .list();

        // 如果没有激活码
        if (activationCodes.isEmpty()) {
            return R.ok().code(500).message("没有有效的激活码");
        }

        // 去重并找出每个 examTypeId 对应的最大有效到期时间
        Map<Long, UserActivationCodes> uniqueExamTypes = new HashMap<>();
        for (UserActivationCodes code : activationCodes) {
            Long examTypeId = code.getExamTypeId();
            // 如果当前 examTypeId 没有记录，或者当前激活码的 validUntil 比已记录的激活码 validUntil 更晚，则替换
            if (!uniqueExamTypes.containsKey(examTypeId) || code.getValidUntil().after(uniqueExamTypes.get(examTypeId).getValidUntil())) {
                uniqueExamTypes.put(examTypeId, code);
            }
        }

        // 获取题库信息并封装返回数据
        List<Map<String, Object>> result = new ArrayList<>();
        for (Long examTypeId : uniqueExamTypes.keySet()) {
            // 根据 examTypeId 获取题库信息，题库 status 必须为 1
            List<ExamLibraries> libraries = libraryService.lambdaQuery()
                    .eq(ExamLibraries::getExamTypeId, examTypeId)
                    .eq(ExamLibraries::getStatus, 1)
                    .list();  // 使用 list() 方法，可能会返回多条记录

            // 如果找到了多个题库记录，可以根据需要做进一步处理
            for (ExamLibraries library : libraries) {
                if (library != null) {
                    // 获取激活码对应的到期时间
                    UserActivationCodes activationCode = uniqueExamTypes.get(examTypeId);
//                    Timestamp validUntil = activationCode.getValidUntil();
                    ZonedDateTime validUntil = activationCode.getValidUntil().toInstant().atZone(ZoneId.of("Asia/Shanghai"));

                    // 创建 Map 以封装数据
                    Map<String, Object> data = new HashMap<>();
                    data.put("examLibraryId", library.getId());          // 题库ID
                    data.put("examLibraryName", library.getName());      // 题库名称
                    data.put("validUntil", validUntil);                  // 激活码的到期时间

                    // 添加到结果列表
                    result.add(data);
                }
            }
        }

        // 返回封装后的数据
        return R.ok().code(200).message("查询成功")
                .data("activationCodeData", result);
    }




}
